<template>
  <h1 data-testid="event-list-title">Events for Good</h1>
  <div class="events">
    <EventCard
      data-testid="event"
      v-for="event in events"
      :key="event.id"
      :event="event"
    />
    <div class="pagination">
      <router-link
        id="page-prev"
        v-if="page !== 1"
        :to="{ name: 'EventList', query: { page: page - 1 } }"
        rel="prev"
      >
        &#60; Previous
      </router-link>
      <router-link
        id="page-next"
        v-if="eventsTotal > page * 4"
        :to="{ name: 'EventList', query: { page: page + 1 } }"
        rel="next"
      >
        Next &#62;
      </router-link>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
import { mapActions, mapState } from 'vuex'
import EventCard from '@/components/EventCard.vue'

export default {
  name: 'EventList',
  props: ['page'],
  components: {
    EventCard,
  },
  computed: {
    ...mapState(['events', 'eventsTotal']),
  },
  created() {
    this.perPage = 4
    this.fetchEvents({ perPage: this.perPage, page: this.page }).catch(() => {
      this.$router.push({ name: 'NetworkError' })
    })
  },
  methods: {
    ...mapActions(['fetchEvents']),
  },
}
</script>

<style scoped>
.events {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pagination {
  display: flex;
  width: 290px;
}
.pagination a {
  flex: 1;
  text-decoration: none;
  color: #2c3e50;
}

#page-prev {
  text-align: left;
}

#page-next {
  text-align: right;
}
</style>
